

//
//  MSSegmentView.m
//  ZXDemo
//
//  Created by 马胜 on 2017/5/16.
//  Copyright © 2017年 SnailMS. All rights reserved.
//

#import "MSSegmentView.h"
//#define DEVICE_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREENW  (self.framessa.size.width)
#define Color_White [UIColor whiteColor]      // 1.0 white
#define RGBACOLOR(r,g,b,a) [UIColor colorWithRed:(r * 1.0)/255.0 green:(g* 1.0)/255.0 blue:(b* 1.0)/255.0 alpha:(a)]
#define BORDER_COLOR  RGBACOLOR(204, 204, 204, 1).CGColor


@interface MSSegmentView ()

@property (nonatomic , strong)  NSMutableArray  *items;
@property (nonatomic , strong)  NSMutableArray  *titleLabels;
@property (nonatomic , strong)  NSMutableArray  *images;
@property (nonatomic , strong)  NSMutableArray  *btnBgViews;
@property(nonatomic,assign) CGRect framessa;
@property (nonatomic, strong) UIScrollView *navgationTabBar;
@property (nonatomic, strong) UIView *line;
@property (nonatomic, strong) NSArray *itemsWidth;
@property (nonatomic, strong) UIView *lineDownView;

@end

@implementation MSSegmentView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.framessa = frame;
        [self initConfig];
        
        self.lineExWidth = 0;
        self.btnInLineHeight = 0;
    }
    return self;
}

- (void)initConfig
{
    _items = [@[] mutableCopy];
    _titleLabels = [@[] mutableCopy];
    _images = [@[] mutableCopy];
    _btnBgViews = [@[] mutableCopy];
    [self viewConfig];
}

- (void)viewConfig
{
    _navgationTabBar = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREENW, self.frame.size.height)];
    _navgationTabBar.backgroundColor = [UIColor clearColor];
    _navgationTabBar.showsHorizontalScrollIndicator = NO;
    [self addSubview:_navgationTabBar];
    _lineDownView = [[UIView alloc] initWithFrame:CGRectMake(0, self.frame.size.height-0.5, self.framessa.size.width, 0.5)];
    _lineDownView.backgroundColor = [UIColor clearColor];
    [self addSubview:_lineDownView];
}

- (void)updateData
{
    _items = [@[] mutableCopy];
    _titleLabels = [@[] mutableCopy];
    _images = [@[] mutableCopy];
    _btnBgViews = [@[] mutableCopy];
    for (UIView *view in _navgationTabBar.subviews) {
        [view removeFromSuperview];
    }
    _itemsWidth = [self getButtonsWidthWithTitles:_itemTitles];
//    [self initConfig];
    if (_itemsWidth.count)
    {
        CGFloat contentWidth = [self contentWidthAndAddNavTabBarItemsWithButtonsWidth:_itemsWidth];
        _navgationTabBar.contentSize = CGSizeMake(contentWidth, 0);
    }
}

- (void)cleanData{
    [_items removeAllObjects];
    _line = nil;
    for (UIView *view in _navgationTabBar.subviews) {
        [view removeFromSuperview];
    }
}

- (CGFloat)contentWidthAndAddNavTabBarItemsWithButtonsWidth:(NSArray *)widths
{
    CGFloat buttonX = 0;
    
    CGFloat padding = self.isFullScreen?0:10.0f;
    
    for (NSNumber *number in _itemsWidth) {
        buttonX += [number floatValue] + padding*2;
    }
    
    if (buttonX>self.framessa.size.width) {
        buttonX = 0;
    }else{
        _navgationTabBar.bounces = NO;
        buttonX = 0;
        for (NSNumber *number in _itemsWidth) {
            buttonX += [number floatValue]+1;
        }
        buttonX--;
        padding = (self.framessa.size.width - buttonX)/(_itemsWidth.count*2);
        buttonX = 0;
    }
    
    for (NSInteger index = 0; index < [_itemTitles count]; index++) {
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        
        if (self.ImageType == MSSegmentBtnImageTypeLeft) {
            
            
            [button setTitle:_itemTitles[index][@"name"] forState:UIControlStateNormal];
            [button setTitle:_itemTitles[index][@"name"] forState:UIControlStateSelected];
            [button setTitleColor:self.textColor forState:UIControlStateNormal];
            [button setTitleColor:self.textSelColor forState:UIControlStateSelected];
            button.titleLabel.font = self.font;
            if (self.itemImages != nil && self.itemImages.count > 0) {
                NSDictionary *imgDict = [self.itemImages objectAtIndex:index];
                [button setImage:GetImage([imgDict objectForKey:@"nor"]) forState:UIControlStateNormal];
                [button setImage:GetImage([imgDict objectForKey:@"sel"]) forState:UIControlStateSelected];
                button.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 5);
                button.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
            }

        }else if (self.ImageType == MSSegmentBtnImageTypeTop){
            
            NSDictionary *imgDict = [self.itemImages objectAtIndex:index];
            UIImageView *imageView = [[UIImageView alloc] initWithImage:GetImage([imgDict objectForKey:@"nor"]) highlightedImage:GetImage([imgDict objectForKey:@"sel"])];
            [button addSubview:imageView];
            [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(button.mas_centerY).with.offset(-4);
                make.centerX.equalTo(button.mas_centerX);
            }];
            
            
            UILabel *titleLabel = [UILabel new];
            [titleLabel setLabelText:_itemTitles[index][@"name"] textColor:self.textColor font:self.font];
            titleLabel.highlightedTextColor = self.textSelColor;
            [button addSubview:titleLabel];
            [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(button);
                make.top.equalTo(button.mas_centerY).with.offset(2);
            }];
            
            [_images addObject:imageView];
            [_titleLabels addObject:titleLabel];

        }
        
        
        
        CGFloat textWith = [[_itemsWidth objectAtIndex:index] floatValue];
        button.frame = CGRectMake(buttonX, 0,textWith + padding*2, self.frame.size.height);
        
        if (self.btnBackgroundColor) {
            UIView *btnBgView = [[UIView alloc] initWithFrame:CGRectMake(buttonX+padding, 7,textWith, self.frame.size.height - 7*2)];
            btnBgView.backgroundColor = self.btnBackgroundColor;
            [_navgationTabBar addSubview:btnBgView];
            [_btnBgViews addObject:btnBgView];
            SET_VIEW_LAYER(btnBgView, (self.frame.size.height - 7*2)/2, 0, Color_White);
        }

        buttonX += button.frame.size.width+1;
        
        [button addTarget:self action:@selector(itemPressed:type:) forControlEvents:UIControlEventTouchUpInside];
        [_navgationTabBar addSubview:button];
        [_items addObject:button];


        if (self.btnInLineHeight && index != _itemTitles.count-1) {
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(button.frame), (self.frame.size.height-self.btnInLineHeight)/2, 1, self.btnInLineHeight)];
            lineView.backgroundColor = self.btnInLineColor;
            [_navgationTabBar addSubview:lineView];
            
        }
        
    }
    
    buttonX--;
    
    [self showLineWithButtonWidth:[widths[0] floatValue]];
    return buttonX;
}



#pragma mark  下划线
- (void)showLineWithButtonWidth:(CGFloat)width
{
    UIButton *btn = _items[0];
    [self itemPressed:btn type:0];

    if (!_line) {
        //第一个线的位置
        _line = [[UIView alloc] initWithFrame:CGRectMake((btn.frame.size.width-width)/2, self.frame.size.height-3.0f, width, 2.0f)];
        _line.backgroundColor = self.lineColor;
        [_navgationTabBar addSubview:_line];
        [self setCurrentItemIndex:0];
    }
    
}

- (void)itemPressed:(UIButton *)button type:(int)type
{    
    if ([self.delegate respondsToSelector:@selector(itemDidSelectedWithIndex:withCurrentIndex:)]) {
        NSInteger index = [_items indexOfObject:button];
        [self.delegate itemDidSelectedWithIndex:index withCurrentIndex:_currentItemIndex];
    }
}

//计算数组内字体的宽度
- (NSArray *)getButtonsWidthWithTitles:(NSArray *)titles;
{
    NSMutableArray *widths = [@[] mutableCopy];
    
    if (self.isFullScreen) {
        
        NSArray *subArray = self.itemTitles!=nil?self.itemTitles:self.itemImages;
        
        NSInteger count = subArray.count;
        CGFloat width = (self.framessa.size.width-(count-1)*0.5)/(CGFloat)count;
        for (NSInteger loop = 0; loop < subArray.count; loop++) {
            [widths addObject:@(width)];
        }
        
    }else{
        
        CGFloat imgsW = 0;
        if (self.itemImages != nil && self.itemImages.count > 0) {
            imgsW = 20;
        }
        
        for (NSDictionary *titleDic in titles)
        {
            NSString *title = titleDic[@"name"];
            CGSize textMaxSize = CGSizeMake(self.framessa.size.width, MAXFLOAT);
            CGSize textRealSize = [title sizeWithFont:self.selFont maxSize:textMaxSize].size;
            
            NSNumber *width = [NSNumber numberWithFloat:textRealSize.width+self.lineExWidth*2 + imgsW];
            [widths addObject:width];
        }
    }
    
    return widths;
}

#pragma mark 偏移
- (void)setCurrentItemIndex:(NSInteger)currentItemIndex
{
    
    for (NSInteger loop = 0; loop < _items.count; loop++) {
        UIButton *btn = _items[loop];
        btn.selected = NO;
        if (self.btnBackgroundColor) {
            UIView *btnBgView = _btnBgViews[loop];
            btnBgView.hidden = YES;
        }
        if (self.ImageType == MSSegmentBtnImageTypeLeft) {
            btn.titleLabel.font = self.font;
        }else{
            UIImageView *imageView = _images[loop];
            UILabel *titleLabel = _titleLabels[loop];
            imageView.highlighted = NO;
            titleLabel.highlighted = NO;
        }
    }
    
    _currentItemIndex = currentItemIndex;
    UIButton *button = _items[currentItemIndex];
    button.selected = YES;
    
    if (self.btnBackgroundColor) {
        UIView *btnBgView = _btnBgViews[currentItemIndex];
        btnBgView.hidden = NO;
    }

    if (self.ImageType == MSSegmentBtnImageTypeLeft) {
        
        button.titleLabel.font = kSystemFont(18);
    }else{
        UIImageView *imageView = _images[currentItemIndex];
        UILabel *titleLabel = _titleLabels[currentItemIndex];
        imageView.highlighted = YES;
        titleLabel.highlighted = YES;
    }

    CGFloat flag = SCREENW;
    
    
    if (button.frame.origin.x + button.frame.size.width + button.frame.size.width/2 >= flag)
    {
        CGFloat offsetX = button.frame.origin.x + button.frame.size.width - flag;
        if (_currentItemIndex < [_itemTitles count]-1)
        {
            offsetX = offsetX + button.frame.size.width;
        }
        [_navgationTabBar setContentOffset:CGPointMake(offsetX, 0) animated:YES];
        
    }
    else
    {
        [_navgationTabBar setContentOffset:CGPointMake(0, 0) animated:YES];
    }
    
    //下划线的偏移量
    [UIView animateWithDuration:0.1f animations:^{
        self.line.frame = CGRectMake(button.frame.origin.x + (button.frame.size.width-[self.itemsWidth[currentItemIndex] floatValue])/2, self.line.frame.origin.y, [self.itemsWidth[currentItemIndex] floatValue], self.line.frame.size.height);
    }];
}

- (void)setDownLineColor:(UIColor *)downLineColor{
    
    _downLineColor = downLineColor;
    _lineDownView.backgroundColor = downLineColor;
}

@end
